package com.rc.saas.tenant.controller.member;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.tenant.TenantUserExample;
import com.rc.saas.tenant.search.member.MemberAccountRecordSearch;
import com.rc.saas.tenant.search.member.MemberAccountSearch;
import com.rc.saas.tenant.search.member.MemberPointRecordSearch;
import com.rc.saas.tenant.service.member.MemberAccountRecordService;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.service.ugs.UgsMemberPointRecordService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.member.MemberAccountRecordResultVo;
import com.rc.saas.tenant.vo.member.MemberAccountResult;
import com.rc.saas.tenant.vo.member.MemberPointRecordResultVo;
import com.rc.saas.tenant.vo.member.MemberRechargeVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author frog
 * @date 2019/11/19
 */
@Controller
@RequestMapping("/memberAccount")
public class MemberAccountController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(MemberAccountController.class);

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;

    @Autowired
    private TenantSmsService tenantSmsService;



    /**
     * 跳转平台钱包页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String memberAccountPage() {
        return "/templates/member/memberAccount/memberAccount";
    }

    /**
     * 返回平台钱包列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listMemberAccount", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listMemberAccount(MemberAccountSearch memberAccountSearch) {
        PageInfo<MemberAccountResult> pageInfo = memberAccountService.searchByCondition(memberAccountSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转余额变动页面
     *
     * @return
     */
    @RequestMapping(value = "/memberAccountRecord/{memberId}", method = RequestMethod.GET)
    public String memberAccountRecordPage(@PathVariable("memberId") Long memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/templates/member/memberAccount/memberAccountRecord";
    }


    /**
     * 返回余额变动列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listMemberAccountRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listMemberAccountRecord(MemberAccountRecordSearch memberAccountRecordSearch) {
        PageInfo<MemberAccountRecordResultVo> pageInfo = memberAccountRecordService.searchByCondition(memberAccountRecordSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转充值页面
     *
     * @return
     */
    @RequestMapping(value = "/recharge/{memberId}", method = RequestMethod.GET)
    public String rechargePage(@PathVariable("memberId") Long memberId, Model model) {
        TenantUser user = getSessionTenantUser();
        //处理手机号中间4位替换成*
        user.setMobile(user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));

        //运营商
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());

        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andTenantCodeEqualTo(tenant.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
        TenantUser adminUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
        model.addAttribute("user", adminUser);
        model.addAttribute("tenant", tenant);
        model.addAttribute("member", memberInfo);

        return "/templates/member/memberAccount/memberRecharge";
    }

    /**
     * 获取手机短信验证码
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/getMemberRechargeAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse getModifyMobileAuthCode(HttpSession session) {
        TenantUser user = ShiroUtils.getSessionUser();

        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
        TenantUser findUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

        logger.info("获取手机短信验证码:{},:{}", findUser.getLoginName(), findUser.getMobile());

        //验证码
        String smscode = uidGenerator.genSmsAuthCode();
        Tenant tenant = tenantService.selectByTenantCode(findUser.getTenantCode());
        SendSmsResponse sendResult = AliyunSmsUtil.sendSms(findUser.getMobile(), smscode, AliyunSmsTemplateEnum.CERTIFY, tenant.getSmsSign());

        if (sendResult == null) {
            logger.error("短信系统异常");
            return TResponse.FAIL("短信系统异常");
        }

        if ("OK".equals(sendResult.getCode())) {
            // 更新sms表
            tenantSmsService.updateTenantSmsByTenantCode(tenant.getPhone(), findUser.getTenantCode(), findUser.getTenantUserId(), "0", "tenant,getMemberRechargeAuthCode:获取验证码:" + findUser.getMobile(), "获取验证码");
        } else {
            logger.error("短信系统异常:" + sendResult.getMessage());
        }

        //将登录验证码保存到会话中
        String sessionAttr = ShiroConstants.SESSION_TENANT_MEMBERRECHARGE_KEY + findUser.getMobile();
        String sessionAuthCode = smscode + System.currentTimeMillis();
        session.setAttribute(sessionAttr, sessionAuthCode);

        logger.error("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", findUser.getMobile(), sessionAttr, sessionAuthCode);

        return TResponse.SUCCESS("验证码已发送");
    }

    /**
     * 新增保存
     *
     * @param memberRecharge
     * @return
     */
    @RequestMapping(value = "/saveRecharge", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse save(HttpSession session, MemberRechargeVo memberRecharge) {
        logger.info("controller.saveRecharge request,:{},:{}", memberRecharge.getMemberId(), memberRecharge.getAuthCode());

        TenantUser user = ShiroUtils.getSessionUser();

        TenantUserExample example = new TenantUserExample();
        example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andUserTypeEqualTo("0").andStatusEqualTo("0");
        TenantUser findUser = tenantUserService.selectByExample(example).stream().findFirst().orElseGet(() -> null);

        String sessionAttr = ShiroConstants.SESSION_TENANT_MEMBERRECHARGE_KEY + findUser.getMobile();
        String sessionAuthCode = (String) session.getAttribute(sessionAttr);
        if (StringUtils.isBlank(sessionAuthCode)) {
            return TResponse.FAIL("未申请验证码");
        }
        if (!memberRecharge.getAuthCode().equals(sessionAuthCode.substring(0, 6))) {
            return TResponse.FAIL("验证码错误");
        }
        if (!Pattern.matches("-?[0-9]+.?[0-9]{0,}", memberRecharge.getAmount().toString())) {
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("充值金额不合法");
        }
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberRecharge.getMemberId());

        if (memberInfo == null) {
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("充值失败，用户不存在");
        }

        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(memberInfo.getMemberId());
        // 0 :个人 1:企业钱包
        if ("1".equals(memberRecharge.getMemberType())) {
            if (!"1".equals(memberInfo.getMemberType())) {
                return TResponse.FAIL("该用户不是企业主会员");
            }

            if ((memberAccount.getEnterpriseAccount().add(memberRecharge.getAmount())).compareTo(BigDecimal.ZERO) < 0) {
                session.removeAttribute(sessionAttr);
                return TResponse.FAIL("扣除企业余额大于企业主会员总余额");
            }


        } else {
//            if ((memberAccount.getAccount().add(memberRecharge.getAmount())).compareTo(BigDecimal.ZERO) < 0) {
//                session.removeAttribute(sessionAttr);
//                return TResponse.FAIL("扣除金额大于用户余额");
//            }
        }


        if (!memberInfo.getTenantCode().equals(user.getTenantCode())) {
            logger.error("会员的运营商不一致,:{},:{}", memberInfo.getTenantCode(), user.getTenantCode());
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("会员的运营商不一致");
        }

        try {
            memberAccountService.saveMemberRecharge(memberRecharge);
            //删除验证码
            //if (!"914401153".equals(user.getTenantCode())) {
            //    session.removeAttribute(sessionAttr);
            //}

           /* if (!memberInfo.getMemberType().equals("3")) {
                chargerClientRouter.sendUserAccount(memberInfo.getMemberId(), memberRecharge.getMemberType());
            }*/


        } catch (Exception e) {
            logger.error("保存信息失败", e);
            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("操作失败");
        }
        return TResponse.SUCCESS();
    }
}
